export default {
  /**
	 * 获取我成为vip的天数
	vk.myfn.user.getVipDay();
	 */
  getVipDay() {
    let vk = uni.vk;
    let time1 = vk.getVuex("$user.userInfo.vip_get_time");
    if (!time1) return 0;
    let time2 = Date.now();
    let { todayStart: todayStart1 } = vk.pubfn.getCommonTime(time1);
    let { todayStart: todayStart2 } = vk.pubfn.getCommonTime(time2);
    let time = todayStart2 - todayStart1;
    let day = time / (1000 * 3600 * 24) + 1;
    return Math.floor(day);
  },
  /**
	 * 自动更新vuex内的用户信息
	vk.myfn.user.getMyInfo();
	 */
  getMyInfo() {
    let vk = uni.vk;
    // 更新vuex内的用户信息
    vk.callFunction({
      url: "client/user.getMyInfo",
    });
  },
  /**
   * 是否是核销员
   * vk.myfn.user.isVerify()
   */
  isVerify() {
    let vk = uni.vk;
    return vk.getVuex("$user.userInfo.is_verify_staff");
  },
  /**
   * 获取我的定位（带缓存）
   * let location = await vk.myfn.user.getLocation();
   */
  async getLocation() {
    let vk = uni.vk;
    let cacheKey = "vkmall-location";
    let cacheTime = 1000 * 35; // 微信限制在开发版或体验版中，30秒内调用getLocation，仅第一次有效，剩余返回fail。
    let location = vk.getStorageSync(cacheKey);
    let nowTime = Date.now();
    if (
      vk.pubfn.isNotNull(location) &&
      nowTime - location.lastTime < cacheTime
    ) {
      return location;
    }
    let getLocationResArr = await uni.getLocation({
      type: "gcj02", //wgs84（gps 坐标） gcj02（国测局坐标）
    });
    if (getLocationResArr[0]) {
      if (vk.pubfn.isNotNull(location)) {
        return location;
      }
      console.error("getLocation-error", getLocationResArr[0].errMsg);
      return;
    }
    let getLocationRes = getLocationResArr[1] || getLocationResArr; // 兼容vue3
    location = {
      latitude: getLocationRes.latitude,
      longitude: getLocationRes.longitude,
      lastTime: nowTime,
    };
    vk.setStorageSync(cacheKey, location);
    return location;
  },
  /**
   * 微信公众号的appid
   * let appid = vk.myfn.user.getH5WeixinAppid();
   */
  getH5WeixinAppid() {
    let vk = uni.vk;
    let appid = vk.getVuex("$app.config.service.weixin.h5-weixin.appid");
    return appid;
  },
  /**
	 * 跳微信公众号授权页面
	vk.myfn.user.getH5WeixinCode({
		scope: "snsapi_userinfo",
		redirect_uri: "",
		state: "openid"
	});
	 */
  getH5WeixinCode(obj = {}) {
    let vk = uni.vk;
    let { appid, scope = "snsapi_userinfo", redirect_uri, state } = obj;
    if (!appid) {
      appid = vk.myfn.user.getH5WeixinAppid();
    }
    if (!redirect_uri) {
      let splitArr = window.location.href.split("/");
      let serviceUrl = splitArr[0] + "//" + splitArr[2];
      redirect_uri = `${serviceUrl}/pages/login/h5-weixin-auth`;
      vk.setStorageSync(
        "vkmall.h5-weixin-auth-redirect-uri",
        window.location.href
      );
    }
    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
    window.location.href = url;
  },
  /**
	 * 微信转账确认收款
	vk.myfn.user.requestMerchantTransfer({
		...data.options,
		success: (res) => {
			// 确认收款成功
			vk.alert("收款成功");
			item.status = 2;
		}
	});
	 */
  requestMerchantTransfer(obj = {}) {
    let vk = uni.vk;
    let { options } = obj;
    let allowRequestMerchantTransfer = false;
    // #ifdef APP || MP-WEIXIN
    allowRequestMerchantTransfer = true;
    // #endif
    // #ifdef WEB
    if (vk.h5.getEnv() === "h5-weixin") {
      allowRequestMerchantTransfer = true;
    }
    // #endif
    if (!allowRequestMerchantTransfer) {
      return;
    }

    const successHandle = (res) => {
      // 标记已确认收款
      if (obj._id) {
        vk.callFunction({
          url: "client/salesman.confirmTransfer",
          data: {
            _id: obj._id,
          },
          needAlert: false,
          complete: () => {
            if (typeof obj.success === "function") {
              obj.success(res);
            }
          },
        });
      } else {
        if (typeof obj.success === "function") {
          obj.success(res);
        }
      }
    };

    const failHandle = (err) => {
      // 确认收款失败
      console.error("err: ", err);
      let errMsg = err.msg || err.errMsg || err.messsage || "收款失败";
      if (errMsg === "requestMerchantTransfer:fail") {
        errMsg = "收款失败";
      } else if (errMsg.indexOf("fail cancel") > -1) {
        errMsg =
          "您取消了收款，建议赶紧再次点击立即收款，否则视为您主动放弃奖励。";
      }
      err.msg = errMsg;
      if (typeof obj.fail === "function") {
        obj.fail(err);
      } else {
        vk.alert(errMsg, "提示", "好的");
      }
    };

    // #ifdef APP || MP-WEIXIN
    uni.requestMerchantTransfer({
      ...options,
      success: (res) => {
        successHandle(res);
      },
      fail: (err) => {
        failHandle(err);
      },
    });
    // #endif
    // #ifdef WEB
    WeixinJSBridge.invoke("requestMerchantTransfer", options, (res) => {
      res.errMsg = res.err_msg;
      if (res.errMsg === "requestMerchantTransfer:ok") {
        // 确认收款成功
        successHandle(res);
      } else {
        // 确认收款失败
        failHandle(res);
      }
    });
    // #endif
  },
};
